<?php
/**
 * 短信发送类
 */

class SMSGateway {

    /**
     * 实例
     * @var SMSGateway
     */
    private static $_instance = null;

    /**
     * 短信类实例
     * @var type
     */
    private $_smsInstances = array();

    /**
     * 构造函数
     */
    private function __construct() {

    }

    /**
     * 获取实例
     * @return type
     */
    public static function getInstance() {

        if (null === self::$_instance) {
            self::$_instance = new self();
        }

        return self::$_instance;
    }
    
    /**
     * 解析手机号，获取 国家 和 实际手机号
     * @param type $mobile
     * @return array
     */
    public static function parseMobile($mobile) {
        
        $match = array();
        // 假定格式：+[国家区号][手机号]
        // [NOTE] 此规则不一定适用于所有国家！开通新国家前务必测试验证
        if (!preg_match('/^\+?(\d{1,3})?(\d{11})$/', $mobile, $match)) {
            throw new Exception('bad mobile number', SMS_Exception::E_PARAM_ERROR);
        }
        return array(
            'country_code' => ltrim($match[1], '0'),
            'mobile_number' => $match[2],
        );
    }

    /**
     * 给指定手机发送短信
     * @param type $mobile
     * @param type $content
     */
    public function send($mobile, $content, $locale = null) {

        if ($locale) {
            $countryCode = $locale;
            $mobileNumber = $mobile;
        } else {
            $info = self::parseMobile($mobile);
            $countryCode = $info['country_code'];
            $mobileNumber = $info['mobile_number'];
        }
        $conf = V::config('smsgateway');
        if (!isset($conf[$countryCode])) {
            throw new Exception('not support', SMS_Exception::E_PARAM_ERROR);
        }
        if (!isset($this->_smsInstances[$countryCode])) {
            $this->_smsInstances[$countryCode] = SMS::factory($conf[$countryCode]);
        }
        return $this->_smsInstances[$countryCode]->send($mobileNumber, $content);
    }
}